/**
 *
 */
package com.iknight.mgr.controller;

import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.PubCodeService;
import com.iknight.mgr.core.base.BaseController;
import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.jstree.JsTreeNode;
import com.iknight.mgr.core.jstree.NodeStatus;
import com.iknight.mgr.core.tree.CodeTreeNode;
import com.iknight.mgr.core.tree.TreeUtils;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.mgr.core.utils.IkgWebUtils;
import com.iknight.mgr.model.CodeModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/rest/pubcode")
public class PubCodeController implements BaseController<CodeModel> {
    @Autowired
    private PubCodeService<CodeModel, String> pubCodeService;
    @Value("${enableRoot}")
    private boolean enableRoot;
    @Value("${rootName}")
    private String rootName;

    @Override
    public CodeModel format(Map<String, Object> params) {
        // TODO Auto-generated method stub
        CodeModel record = new CodeModel();
        record.setCode_id(IkgStringUtils.ObjectToString(params.get("code_id")));
        if (IkgStringUtils.isNotNull(params.get("code_value"))) {
            record.setCode_value(IkgStringUtils.ObjectToString(params.get("code_value")));
        }
        if (IkgStringUtils.isNotNull(params.get("code_text"))) {
            record.setCode_text(IkgStringUtils.ObjectToString(params.get("code_text")));
        }
        if (IkgStringUtils.isNotNull(params.get("p_code_id"))) {
            record.setP_code_id(IkgStringUtils.ObjectToString(params.get("p_code_id")));
        }
        return record;
    }

    @Override
    @RequestMapping("/save")
//	@RequiresPermissions("mgr.code.save")
//	@RequiresRoles("admin")
    public Object save(@RequestBody Map<String, Object> params, HttpServletRequest request,
                       HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        CodeModel record = format(params);
        pubCodeService.save(record);
        return IkgWebUtils.postIkgResponse(true, "查询成功!", IkgConstantCode.OPERSUCCESS);
    }

    @Override
    @RequestMapping("/delete")
//	@RequiresPermissions("mgr.code.delete")
//	@RequiresRoles("admin")
    public Object delete(@RequestBody Map<String, Object> params, HttpServletRequest request,
                         HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        pubCodeService.delete(IkgStringUtils.ObjectToString(params.get("code_id")));
        return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
    }

    @Override
//	@RequiresPermissions("mgr.code.selectOne")
    public Object selectOne(@RequestBody Map<String, Object> params, HttpServletRequest request,
                            HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        CodeModel record = pubCodeService.selectOne(IkgStringUtils.ObjectToString(params.get("code_id")));
//        return IkgWebUtils.postMsg(record);
        return IkgWebUtils.postIkgResponse(true, "查询成功!", record);
    }

//    @RequestMapping("/selectByCond")
//    public Object selectByCond(@RequestBody Map<String, Object> params, HttpServletRequest request,
//                               HttpServletResponse response) {
//        // TODO Auto-generated method stub
//        if (null == params) {
//            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
//        }
//        List<CodeModel> result = pubCodeService.selectByCond(params);
////        return IkgWebUtils.postMsg(result);
//        return IkgWebUtils.postIkgResponse(true, "查询成功!", result);
//    }

    @RequestMapping("/options")
    public Object selectOptions(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                HttpServletResponse response) {
        List<Map> options = pubCodeService.getOptionsByPId(IkgStringUtils.ObjectToString(params.get("p_code_id")));
        return options;
    }

    @Override
    @RequestMapping("/list")
    public Object selectByPage(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (null == params) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        int pageIndex = IkgStringUtils.ObjectToInt(params.get("pageNumber"));
        int pageSize = IkgStringUtils.ObjectToInt(params.get("pageSize"));
        // return null;
        PageInfo<CodeModel> codes = pubCodeService.selectPage(params, pageIndex, pageSize);
        return IkgWebUtils.postResult(codes.getTotal(), codes.getList());
    }

    @Override
    public boolean isPKeyNotNull(Map<String, Object> params) {
        // TODO Auto-generated method stub
        return null != params && null != params.get("code_id");
    }

    @Deprecated
    @RequestMapping("/selectAll")
    public Object selectAll(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        List<Map> codes = pubCodeService.getAllCode();
        List<CodeTreeNode> codeTree = new ArrayList<CodeTreeNode>();
        if (null == codes || codes.size() == 0) {
            return null;
        }
        Iterator<Map> ita = codes.iterator();
        while (ita.hasNext()) {
            Map map = ita.next();
            CodeTreeNode node = new CodeTreeNode();
            node.setId(IkgStringUtils.ObjectToString(map.get("code_id")));
            node.setCode_value(IkgStringUtils.ObjectToString(map.get("code_value")));
            node.setText(IkgStringUtils.ObjectToString(map.get("code_text")));
            if (IkgStringUtils.isNotNull(map.get("p_code_id"))) {
                node.setPid(IkgStringUtils.ObjectToString(map.get("p_code_id")));
            }
            codeTree.add(node);
        }
        List<CodeTreeNode> treeNodes = TreeUtils.getRootNode(codeTree);
        return JSONArray.fromObject(treeNodes);
    }

    @PostMapping("/getTreeNodes")
    public Object lazyLoadTree(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        String nodeId = IkgStringUtils.ObjectToString(params.get("nodeId"));
        if (nodeId.equals("#")) {
            nodeId = "";
        }
        JsTreeNode rootNode = new JsTreeNode();


        List<Map> result = pubCodeService.getTreeNode(nodeId);

        List<JsTreeNode> treeNodes = new ArrayList<>();

        if (enableRoot) {

            rootNode.setId(UUID.randomUUID().toString());
            rootNode.setText(rootName);
            rootNode.setParent("#");
            rootNode.setState(new NodeStatus(false, false, false, false));
            JSONObject rootAttr = new JSONObject();
            rootAttr.put("isRoot", true);
            rootNode.setAttributes(rootAttr);

            treeNodes.add(rootNode);
        }

        Iterator<Map> ita = result.iterator();
        while (ita.hasNext()) {
            Map map = ita.next();
            JsTreeNode jsTreeNode = new JsTreeNode();

            jsTreeNode.setId(IkgStringUtils.ObjectToString(map.get("code_id")));
            jsTreeNode.setText(IkgStringUtils.ObjectToString(map.get("code_text")));
            JSONObject attr = new JSONObject();
            attr.put("code_value", IkgStringUtils.ObjectToString(map.get("code_value")));

            jsTreeNode.setAttributes(attr);
            jsTreeNode.setState(new NodeStatus(false, false, false, false));

            if (IkgStringUtils.ObjectToString(IkgStringUtils.ObjectToString(map.get("p_code_id"))).length() == 0 && enableRoot) {
                if (enableRoot) {
                    jsTreeNode.setParent(rootNode.getId());
                } else {
                    jsTreeNode.setParent("#");
                }
            } else {
                jsTreeNode.setParent(IkgStringUtils.ObjectToString(map.get("p_code_id")));
            }

            treeNodes.add(jsTreeNode);
        }

        return JSONArray.fromObject(treeNodes);
    }
}
